package com.hmall.gateway.filter;


import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.util.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@EnableConfigurationProperties(AuthProperties.class)
@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;

    private final AntPathMatcher antPathMatcher;

    private final JwtTool jwtTool;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 获取请求体
        ServerHttpRequest request = exchange.getRequest();

        // 2. 判断请求路径是否需要认证
        String path = request.getPath().toString();
        if(authProperties.getExcludePaths().stream().anyMatch(excludePath -> antPathMatcher.match(excludePath, path))){
            return chain.filter(exchange);
        }
        Long userId = null;
        // 3. 若需要则使用jwt进行认证
        try {
            userId = jwtTool.parseToken(request.getHeaders().getFirst("Authorization"));
        } catch (Exception e) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        // 4. 认证成功将用户id放入请求头中
        String userInfo = userId.toString();
        ServerWebExchange serverWebExchange = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();

        // 5. 放行
        return chain.filter(serverWebExchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
